import api from '../../../utils/api';
import dayjs from '../../../plugin/dayjs/index';
// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
		signbtn: false,
		huise: '',
		sign: false,
		newdaytime: null,
		dateString: '',
		spot: [],
		total: 0,
		getlist: [],
		daily_data_dev:[{
			imgurl:'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/dailyAttendance/green.png',
			name:'已摄入',
			unit:'千卡',
			num:'0'
		},{
			imgurl:'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/dailyAttendance/blue.png',
			name:'今日还可以摄入',
			unit:'千卡',
			num:'0'
		},{
			imgurl:'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/dailyAttendance/red.png',
			name:'已消耗',
			unit:'千卡',
			num:'0'
		}],
		hxhealthlist: [
			{
				id: 'weight',
				state: false,
				name: '体重管理，记录每日体重变化>>',
				urlPage: '/weightManagement/pages/home/index',
				icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/icontz.png'
			},
			{
				id: 'run',
				state: false,
				name: '运动管理，记录每日步数能耗>>',
				urlPage: '/dietaryRecommendations/pages/sportsrecord/index',
				icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/paobu.png'
			},
			{
				id: 'food',
				state: false,
				name: '膳食管理，记录每日膳食摄入>>',
				urlPage: '/dietaryRecommendations/pages/enterfood/index',
				icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/canyin.png'
			}
		],
		recommend: {}
	},
	/**
   * 生命周期函数--监听页面加载
   */
	onLoad: function(options) {
		
	},
	popup(){
		this.setData({
		  signbtn:!this.data.signbtn
		})
	  }, 
	load() {
		// 获取当前日期
		var currentDate = new Date();

		// 获取当月第一天
		var firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
		var formattedFirstDay = formatDate(firstDay); // 转换格式为'YYYY-MM-DD'

		// 获取当月最后一天
		var lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
		var formattedLastDay = formatDate(lastDay); // 转换格式为'YYYY-MM-DD'

		// 格式化日期为'YYYY-MM-DD'
		function formatDate(date) {
			var year = date.getFullYear();
			var month = (date.getMonth() + 1 < 10 ? '0' : '') + (date.getMonth() + 1);
			var day = (date.getDate() < 10 ? '0' : '') + date.getDate();
			return year + '-' + month + '-' + day;
		}
		this.setData({
			formattedFirstDay,
			formattedLastDay
		});
	},
	doGetDatetimefoodRecommend() {
		api.get('/api/hxhealth/datetimefood/recommend')
			.then((res) => {
				if (res.length > 0) {
					this.setData({
						recommend: res[0],
						total: res[0].total,
					})
					this.getlist(this.data.formattedFirstDay, this.data.formattedLastDay);
				}
			})
	},
	getMonthStartEndDate(date) {
		// 给定时间
		var givenDate = new Date(date);

		// 获取给定时间的年份和月份
		var givenYear = givenDate.getFullYear();
		var givenMonth = givenDate.getMonth();

		// 创建给定时间所在月份的开始时间对象
		var startOfMonth = new Date(givenYear, givenMonth, 1);
		startOfMonth.setHours(0, 0, 0, 0);

		// 创建下个月的开始时间对象
		var nextMonth = givenMonth + 1;
		var startOfNextMonth = new Date(givenYear, nextMonth, 1);
		startOfNextMonth.setHours(0, 0, 0, 0);

		// 获取给定时间所在月份的结束时间对象
		var endOfMonth = new Date(startOfNextMonth.getTime() - 1);

		// 格式化开始时间
		var formattedStart = startOfMonth.getFullYear() + '-' + (startOfMonth.getMonth() + 1).toString().padStart(2, '0') + '-' + startOfMonth.getDate().toString().padStart(2, '0');

		// 格式化结束时间
		var formattedEnd = endOfMonth.getFullYear() + '-' + (endOfMonth.getMonth() + 1).toString().padStart(2, '0') + '-' + endOfMonth.getDate().toString().padStart(2, '0');
		return {
			formattedStart,
			formattedEnd
		}
	},
	dateChange(e) {
		let data_dev_totalFood = this.data.daily_data_dev
		data_dev_totalFood[0].num = 0
		data_dev_totalFood[1].num = 0
		data_dev_totalFood[2].num = 0
		this.setData({
				daily_data_dev: data_dev_totalFood
		})
		const monthDateOb = this.getMonthStartEndDate(e.detail.dateString)
		this.setData({
			dateString: e.detail.dateString
		});
		wx.setStorageSync('dateString', this.data.dateString)
		this.getlist(monthDateOb.formattedStart, monthDateOb.formattedEnd)
		if (this.data.spot.length > 0) {
			console.log(this.data.spot);
			const array = this.data.getlilst;
			this.setData({
				sign: false,
				huise: 'huise'
			});
			var hxhealthlistsate = [
				{
					id: 'weight',
					state: false,
					name: '体重管理，记录每日体重变化>>',
					urlPage: '/weightManagement/pages/home/index',
					icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/icontz.png'
				},
				{
					id: 'run',
					state: false,
					name: '运动管理，记录每日步数能耗>>',
					urlPage: `/dietaryRecommendations/pages/sportsrecord/index?curDate=${this.data.dateString}`,
					icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/paobu.png'
				},
				{
					id: 'food',
					state: false,
					name: '膳食管理，记录每日膳食摄入>>',
					urlPage: `/dietaryRecommendations/pages/enterfood/index?curDate=${this.data.dateString}`,
					icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/canyin.png'
				}
			]
			for (let i = 0; i < array.length; i++) {
				if (this.data.dateString == array[i].date) {
					console.log(array[i].date === formatTime(),'999');
					if(array[i].signin == 'true') {
						console.log('000000');
						this.setData({
							sign: true,
							huise: array[i].date === formatTime() ? '' : 'huise'
						});
					}
					if (array[i].weight == 'true') {
						hxhealthlistsate[0].state = 'true';
					}
					if (array[i].run == 'true') {
						this.getlistdate(this.data.dateString)
						hxhealthlistsate[1].state = 'true';
					}
					if (array[i].food == 'true') {
						// this.getlistfood(this.data.dateString)
						hxhealthlistsate[2].state = 'true';
					}
					// list.push(array[i].date);
				}
			}
			this.setData({
				hxhealthlist: hxhealthlistsate
			});
		}
	},
	getlist(begindate, enddate) {
		api
			.post('/api/hxhealth/signin/list', {
				data: {
					begindate,
					enddate
				}
			})
			.then((res) => {
				console.log(res);
				const array = res;
				let list = [];
				var hxhealthlistsate = [
					{
						id: 'weight',
						state: false,
						name: '体重管理，记录每日体重变化>>',
						urlPage: '/weightManagement/pages/home/index',
						icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/icontz.png'
					},
					{
						id: 'run',
						state: false,
						name: '运动管理，记录每日步数能耗>>',
						urlPage: `/dietaryRecommendations/pages/sportsrecord/index?curDate=${this.data.dateString}`,
						icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/paobu.png'
					},
					{
						id: 'food',
						state: false,
						name: '膳食管理，记录每日膳食摄入>>',
						urlPage: `/dietaryRecommendations/pages/enterfood/index?curDate=${this.data.dateString}`,
						icon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/dietaryRecommendations/canyin.png'
					}
				]
				for (let i = 0; i < array.length; i++) {
					if (array[i].signin == 'true') {
						list.push(array[i].date);
					}
					if (this.data.dateString == array[i].date) {
						if(array[i].signin == 'true') {
							this.setData({
								sign: true,
								huise: array[i].date === formatTime() ? '' : 'huise'
							});
						}
						if (array[i].weight == 'true') {
							hxhealthlistsate[0].state = 'true';
						}
						if (array[i].run == 'true') {
							this.getlistdate(this.data.dateString)
							hxhealthlistsate[1].state = 'true';
						}
						if (array[i].food == 'true') {
							// this.getlistfood(this.data.dateString)
							hxhealthlistsate[2].state = 'true';
						}
						// list.push(array[i].date);
					}
				}

				this.setData({
					hxhealthlist: hxhealthlistsate,
					getlilst: res,
					spot: list
				});
				const findV = this.data.getlilst.find(item => item.date === this.data.dateString)
				let data_dev_totalFood = this.data.daily_data_dev
				data_dev_totalFood[0].num = Number(findV.intake).toFixed(1) || 0
				data_dev_totalFood[1].num = (Number(this.data.total) - data_dev_totalFood[0].num).toFixed(1)
				this.setData({
						daily_data_dev: data_dev_totalFood
				})
			})
			.catch((e) => {
				console.log('error', e);
			});
	},
	signin(e) {
		console.log(e);
		console.log(this.data.huise == 'huise');
		if(this.data.huise == 'huise') {
			// wx.showToast({
			// 	icon: 'none',
			// 	title: '不可签到！'
			// });
			return
		}
		if(this.data.huise == 'huise' || e.target.dataset.type == 'true') {
			wx.showToast({
				icon: 'none',
				title: '已签到！'
			});
			return
		}
		const url = `/api/hxhealth/signin/sign`;
		const options = {
            data: {},
            head: {},
            isCookie: true
        }
		api
			.get(url,options,true)
			.then((res) => {
				console.log(res);
				// wx.showToast({
				// 	icon: 'none',
				// 	title: '签到成功！'
				// });
				this.popup()
				this.setData({
					sign: true
				});
				this.getlist(this.data.formattedFirstDay, this.data.formattedLastDay);
			})
			.catch((e) => {
				console.log(e.faultstring);
				wx.showToast({
					icon: 'none',
					title: e.faultstring
				});
			});
	},
	go(e) {
		console.log(e);
		const { titlename, urlpage } = e.currentTarget.dataset;
		console.log(urlpage, 'page111');
		wx.setStorageSync('recommend', this.data.recommend);
		wx.navigateTo({
			url: `${urlpage}?titlename=${titlename}`
		});
	},
	changestate(e) {
		console.log(e.currentTarget.dataset);
		const num = e.currentTarget.dataset;
		const arry = this.data.hxhealthlist;
		arry[num.index].state = !e.currentTarget.dataset.state;
		this.setData({
			hxhealthlist: arry
		});
	},
	getlistfood(time) {
		api.post('/api/hxhealth/datetimefood/datecal', {
		  data: {
			"date": time
		  }
		}).then(res => {
		}).catch(e => {
		  console.log(e)
		})
	  },
	getlistdate(time) {
		api.post('/api/hxhealth/sportrecord/list', {
		  data: {
			"date": time
		  }
		}).then(res => {
			if (res.length > 0) {
				let data_dev_totalFood = this.data.daily_data_dev
				data_dev_totalFood[2].num = Number(res[0].kcal).toFixed(1) || 0
				this.setData({
					daily_data_dev: data_dev_totalFood
				})
			}
		}).catch(e => {
		  console.log(e)
		})
	},
	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow: function() {
		console.log('onShow')
		this.setData({
			newdaytime: formatTime()
		});
		this.load();
		this.doGetDatetimefoodRecommend()
	},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide: function() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload: function() {},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh: function() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom: function() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage: function() {}
});
